package com.learn.shop.controller;

import com.github.pagehelper.PageInfo;
import com.learn.shop.constant.R;
import com.learn.shop.mapper.SNovelDetailsMapper;
import com.learn.shop.pojo.entriy.SNovelDetails;
import com.learn.shop.pojo.vo.SNovelDetailsVo;
import com.learn.shop.service.SNovelDetailsService;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("SNovelDetails")
public class SNovelDetailsController {

    @Autowired
    private SNovelDetailsService sNovelDetailsService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping("/list")
    @ApiOperation("小说列表")
    public R<PageInfo<SNovelDetails>> novelList(@RequestBody SNovelDetailsVo detailsVo) {
        PageInfo<SNovelDetails> pageInfo = null;
        try {
            pageInfo = sNovelDetailsService.list(detailsVo);
            return R.ok(pageInfo, "查询成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("查询失败!");
        }
    }

    @GetMapping("/getNovels")
    @ApiOperation("获取已存在的小说")
    public R novelLists() {

        //获取MongoDB数据库所有小说集合
        Set<String> collectionNames = mongoTemplate.getCollectionNames();
        List<Map<String, String>> list = new ArrayList<>();
        collectionNames.forEach(res -> {
            Map<String, String> map = new HashMap<>();
            map.put("novelName", res);
            list.add(map);
        });
        return R.ok(list);
    }

    @PostMapping("/editNovel")
    @ApiOperation("编辑小说")
    public R editNovel(@RequestBody SNovelDetails sNovelDetails) {
        try {
            sNovelDetailsService.update(sNovelDetails);
            return R.ok("修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("修改失败!");
        }
    }

    @PostMapping("/addNovel")
    @ApiOperation("新增小说")
    public R addNovel(@RequestBody SNovelDetails sNovelDetails) {
        try {
            sNovelDetailsService.insert(sNovelDetails);
            return R.ok("新增成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("新增失败!");
        }
    }

    @GetMapping("/deleteNovel/{id}")
    @ApiOperation("删除小说")
    public R deleteNovel(@PathVariable Integer id) {
        try {
            sNovelDetailsService.deleteById(id);
            return R.ok("删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("删除失败!");
        }
    }
}
